import 'dart:async';

import 'package:dio/dio.dart';
import 'package:grocery_app_demo/api/entity/scm_response.dart';
import 'package:grocery_app_demo/api/interceptor/response_intercertor.dart';
import 'package:pretty_dio_logger/pretty_dio_logger.dart';

import 'interceptor/add_header_interceptor.dart';

class ScmApi {
  static const String login = '/admin-api/system/auth/login';
  static const String listSupplierByType =
      '/admin-api/tms/suppliers/list-by-type';
  static const String listWarehouse = '/admin-api/tms/warehouse/list';
  static const String listShipper = '/admin-api/tms/shipper/list';
  static const String listGoods = '/admin-api/tms/goods/list';
  static const String refreshToken = '/admin-api/system/auth/refresh-token';
  static const String waitForPurchaseGoods =
      '/admin-api/tms/purchases/wait-for-purchase-goods';

  static final ScmApi instance = ScmApi._internal();
  static final Dio dio = Dio();

  factory ScmApi() {
    return instance;
  }

  ScmApi._internal() {
    dio.options.baseUrl = 'http://scm-uat.meiweitech.com';
    // 5s
    dio.options.connectTimeout = 5000;
    dio.options.receiveTimeout = 3000;
    dio.interceptors.add(AddHeaderInterceptor());
    dio.interceptors.add(ResponseInterceptor());
    dio.interceptors.add(PrettyDioLogger());
  }

  Future<R> get<R>(String path, {Map<String, dynamic>? data}) async {
    var res = await dio.get(path, queryParameters: data);
    return convertRes<ScmRes, R>(res.data);
  }

  Future<List<R>> getList<R>(String path, {Map<String, dynamic>? data}) async {
    var res = await dio.get(path, queryParameters: data);
    return convertRes<ScmResList, R>(res.data);
  }

  Future<R> post<R>(String path,
      {dynamic data, Map<String, dynamic>? queryParameters}) async {
    var res =
        await dio.post(path, data: data, queryParameters: queryParameters);
    return convertRes<ScmRes, R>(res.data);
  }

  Future<List<R>> postList<R>(String path, dynamic data) async {
    var res = await dio.post(path, data: data);
    return convertRes<ScmResList, R>(res.data);
  }

  // 这里是解析泛型json的地方
  dynamic convertRes<T, R>(Map<String, dynamic> response) {
    if (T.toString() == "ScmRes<dynamic>") {
      var rs = ScmRes<R>.fromJson(response);
      if (rs.success) {
        return rs.getResults<R>();
      }
    } else {
      var rs = ScmResList<R>.fromJson(response);
      return rs.getList<R>();
    }
  }
}
